﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.Aparts.Web.Handlers;
using blackhouse.Aparts.Web.Model;
using blackhouse.Aparts.Web.Modules;
using blackhouse.Aparts.Web.Presenter;
using blackhouse.Aparts.Web.View;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business.Opinions;
using blackhouse.BlackApart.Web;
using blackhouse.JavaScript.JQuery;
using blackhouse.mojoPortalExtend.Breadcrumbs;
using blackhouse.Web;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace blackhouse.Aparts.Web.Pages {
    public partial class Opinions : NonCmsBasePage, IOpinionsView {

        #region Fields

        private OpinionsPresenter presenter;
        private int apartmentTypeId = -1;
        private PageSettings cmsPage;
        private double averageReviews;
        private int opinionsCount;
        private int satisfactedClients;

        #endregion

        #region Properties

        public PageSettings CMSPage {
            get {
                if (this.cmsPage == null)
                    this.cmsPage = CacheHelper.GetCurrentPage();
                return this.cmsPage;
            }
        }

        public double AverageReviews {
            get { return this.averageReviews; }
            set {
                this.averageReviews = value;
                this.ltlAvgOpinions.Text = value.ToString("F2");
            }
        }

        public int OpinionsCount {
            get {
                return this.opinionsCount;
            }
            set {
                this.opinionsCount = value;
                this.ltlTotalOpinions.Text = value.ToString();
            }
        }

        public int SatisfactedClients {
            get {
                return this.satisfactedClients;
            }
            set {
                this.satisfactedClients = value;
                this.ltlClients.Text = value.ToString();
            }
        }

        public int ApartmentTypeId {
            get {
                if (this.apartmentTypeId == -1)
                    this.apartmentTypeId = this.GetApartmentTypeId();
                return this.apartmentTypeId;
            }
        }

        public IDictionary<string, double> ReviewCategoriesValue {
            get {
                return this.rptSummaryReviewCategories.DataSource as IDictionary<string, double>;
            }
            set {
                this.rptSummaryReviewCategories.DataSource = value;
            }
        }

        public IList<IOpinion> DisplayOpinions {
            get {
                return this.rptOpinions.DataSource as IList<IOpinion>;
            }
            set {
                this.rptOpinions.DataSource = value;
            }
        }

        private bool haveOpinionAdminPriv;
        private bool haveOpinionAdminPrivSetted;

        public bool HaveOpinionAdminPriv {
            get {
                if (!this.haveOpinionAdminPrivSetted) {
                    this.haveOpinionAdminPriv = WebUser.IsAdminOrContentAdminOrContentPublisher || WebUser.IsInRole("Opinions");
                    this.haveOpinionAdminPrivSetted = true;
                }
                return this.haveOpinionAdminPriv;
            }
        }

        #endregion

        #region Methods

        protected override void OnPreInit(EventArgs e) {
            this.AllowSkinOverride = true;
            HttpContext.Current.Items.Add("skin", "blackhouse");
            HttpContext.Current.Items.Add("short-top", true);


            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            if (this.IsPostBack) {
                int atid = 0;
                string sAT = Request[this.apartmentType.UniqueID];
                if (!string.IsNullOrEmpty(sAT) && Int32.TryParse(sAT, out atid) && atid != this.ApartmentTypeId)
                    Response.Redirect(this.GetOpinionUrl() + "?apartment=" + atid);

            }

            this.AddClassToBody("short-top");
            this.presenter = new OpinionsPresenter(this, new ApartsOpinionsModel());
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            this.presenter.LoadSummaryReviews();
            if (this.RequestHtmlSnapshot())
                this.presenter.LoadAllOpinions();
            else
                this.presenter.LoadOpinions();

            this.DataBind();
            if (!this.RequestHtmlSnapshot())
                this.SupportAjaxContent();

            this.SetSeo();
            this.apartmentType.Value = this.ApartmentTypeId.ToString();

            this.AdditionalMetaMarkup = "<meta name=\"fragment\" content=\"!\">";
        }

        private string GetOpinionUrl() {
            string url = this.CMSPage.Url;
            url = url.ReplaceEx("~/", "/");
            if (url.EndsWith("/"))
                url = url.Substring(0, url.Length - 1);
            return url;
        }

        private void SetSeo() {
            PageProvider page = PageProvider.Instance();
            page.SetPageTitle(this.CMSPage.PageTitle);
            string url = this.GetOpinionUrl();
            page.SetCanonicalUrl(url);
            page.SetPageDescription(this.CMSPage.PageMetaDescription);
            page.SetPageKeywords(this.CMSPage.PageMetaKeyWords);
            this.SetBreadcrumb(this.CMSPage.PageName, url);
        }

        private void SetBreadcrumb(string name, string url) {
            int apartmentTypeId = this.GetApartmentTypeId();
            IApartmentGroup apartment = null;
            if (apartmentTypeId > 0)
                apartment = blackhouse.BlackApart.Business.Factory.Instance().GetApartmentGroup(apartmentTypeId);
            BreadcrumbsAccess breadcrumbs = new BreadcrumbsAccess();
            breadcrumbs.AddCrumb(name, url);
            if (apartment != null)
                breadcrumbs.AddCrumb(apartment.ShortName, url + "?apartment=" + apartment.Id);
        }

        private int GetApartmentTypeId() {
            int apartmentTypeId = 0;
            string sApartment = Request.QueryString["apartment"];
            if (!string.IsNullOrEmpty(sApartment) && Int32.TryParse(sApartment, out apartmentTypeId))
                return apartmentTypeId;
            else
                return 0;
        }

        private bool RequestHtmlSnapshot() {
            return Request.QueryString.AllKeys.Contains("_escaped_fragment_");
        }

        public void SupportAjaxContent() {
            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeJQueryTemplates();
            jql.IncludeJQueryWaypoints();

            ApartmentInfo.AdJs();

            jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.opinions.js,blackhouse.Aparts.Web");
            jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.opinion-apartments.js,blackhouse.Aparts.Web");

            blackhouse.Web.Controls.TemplateControl.TemplateControl tplCtrl = new blackhouse.Web.Controls.TemplateControl.TemplateControl();
            tplCtrl.TemplateId = "opinion-item";
            tplCtrl.Controls.Add(Page.LoadControl("~/Modules/OpinionItem.ascx"));
            this.Page.Header.Controls.Add(tplCtrl);
        }

        public override void DataBind() {
            this.rptOpinions.DataBind();
            this.rptSummaryReviewCategories.DataBind();

            base.DataBind();
        }

        public void ShowNoOpinionsInfo() {
            this.opinionsLoad.Visible = false;
            this.noOpinions.Visible = true;
        }

        #endregion

    }
}